/**
 * @author Yuqi Chou
 * @version  Apr 26, 2012
 */
package org.nerv.web.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * @author Yuqi Chou 
 * @version Apr 26, 2012  5:01:28 PM
 */
public class UploadHandlerServlet extends HttpServlet {
	
	String savePath;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		savePath=config.getInitParameter("SAVEPATH");
	}
	
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
		super.service(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
		super.service(req, resp);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
		
		
		ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
		
        try {
			List<DiskFileItem> fileItems = upload.parseRequest(req);
			for (DiskFileItem fileItem : fileItems) {
				fileItem.write(new File(savePath+"/"+fileItem.getName()));
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
}
